/* eslint-disable no-useless-escape */
/* eslint-disable no-undef */
/* eslint-disable prefer-destructuring */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable consistent-return */
/* eslint-disable @typescript-eslint/no-var-requires */
const fs = require("fs");
const path = require("path");
// 判断文件类型是js或者ts 文件
const judgeJSXFile = (path) => {
  if (!path) {
    return;
  }
  const fileType = path.split(".")[1];
  if (fileType === "tsx") {
    return true;
  }
};
// 读取文件
const readFile = (url) => {
  return new Promise((resolve) => {
    fs.readFile(url, "utf-8", (err, data) => {
      if (err) {
        throw Error(err);
      }
      console.log(`读取${url}成功！`);
      resolve(data);
    });
  });
};
// 写一个文件
const writeFile = (path, data) => {
  return new Promise((resolve) => {
    fs.writeFile(path, data, (err) => {
      if (err) {
        console.log("err", err);
        return;
      }
      console.log(`${path} 写入成功!`);
      resolve();
    });
  });
};
// 读取文件目录
const listFile = (dir, list = []) => {
  const arr = fs.readdirSync(dir);
  arr.forEach((item) => {
    const fullpath = path.join(dir, item);
    const stats = fs.statSync(fullpath);
    if (stats.isDirectory()) {
      listFile(fullpath, list);
    } else if (judgeJSXFile(fullpath)) {
      list.push(fullpath);
    }
  });
  return list;
};

(async () => {
  const jsonFile = await readFile("./target.json");
  const defaultLanguageJson = JSON.parse(jsonFile);
  listFile("./src").forEach(async (item) => {
    const codeFileTmp = await readFile(item);
    let codeFile = "";
    for (const i in defaultLanguageJson) {
      const itemObj = defaultLanguageJson[i];
      if (!itemObj) {
        const textReg = new RegExp(`"${itemObj}"`, "gm");
        if (textReg.test(codeFileTmp)) {
          if (codeFile.indexOf("useGlobalCommonData") === -1) {
            if (textReg.test(codeFileTmp)) {
              codeFile = `import { useGlobalCommonData } from "context/globalContext";\n${codeFile}`;
            }
          }
          const funNameReg = /^(export)\s{1,}(default)\s{1,}(\S*)\;$/gm;
          const funNameRegContainBrackets = /\((.*)\)/g;
          const resu = funNameReg.exec(codeFile);
          let funName = resu && resu[3];
          if (funName) {
            // funName 是 'React.memo(AreaDetailsModal)'
            // 摘出 AreaDetailsModal
            const funNameTmp = funNameRegContainBrackets.exec(funName);
            if (funNameTmp) {
              funName = funNameTmp[1];
            }
            const funNameCode = new RegExp(
              `${funName}\\s{1,}=\\s{1,}(.*)\\s{0,}=>\\s{0,}{$`,
              "gm"
            );
            if (codeFile.indexOf("useGlobalCommonData()") === -1) {
              const funNameCodeLine =
                codeFile.match(funNameCode) && codeFile.match(funNameCode)[0];
              codeFile = codeFile.replace(
                funNameCode,
                `${funNameCodeLine}\n  const { commonInfo }:any = useGlobalCommonData();\n`
              );
            }
          }
        }
        // 正则修改
        if (codeFile) {
          codeFile = codeFile.replace(textReg, `commonInfo["${i}"]`);
        } else {
          codeFile = codeFileTmp.replace(textReg, `commonInfo["${itemObj}"]`);
        }
      }
    }
    await writeFile(item, codeFile);
  });
})();
